package blockr.util;

public class Byte_KMP {
    private static int kmp(byte[] str, byte[] dest, int[] next) {//str文本串  dest 模式串
        for (int i = 0, j = 0; i < str.length; i++) {
            while (j > 0 && str[i] != dest[j]) {
                j = next[j - 1];
            }
            if (str[i] == dest[j]) {
                j++;
            }
            if (j == dest.length) {
                return i - j + 1;
            }
        }
        return 0;
    }

    private static int[] kmpnext(byte[] dest) {
        int[] next = new int[dest.length];
        next[0] = 0;
        for (int i = 1, j = 0; i < dest.length; i++) {
            while (j > 0 && dest[j] != dest[i]) {
                j = next[j - 1];
            }
            if (dest[i] == dest[j]) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static int find(byte[] bytes) {
        byte[] IC_CODE = {15, -1, -16};
        int[] next = kmpnext(IC_CODE);
        return kmp(bytes, IC_CODE, next);
    }
}

